import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:x3_form_core/provider/base_request_form_provider.dart';
import 'package:x3_form_core/business_components/base_request_form_container.dart';

class BaseRequestFormDate extends StatefulWidget {
  BaseRequestFormDate({Key key, @required this.request, this.requestSaveData, this.fromNowOn = false}) : super(key: ValueKey(request.fieldName));

  final BaseHttpRequestModel request;

  final RequestSaveData requestSaveData;

  final bool fromNowOn;

  @override
  _BaseRequestFormDateState createState() => _BaseRequestFormDateState();
}

class _BaseRequestFormDateState extends State<BaseRequestFormDate> {
  BaseRequestFormProvider get _baseRequestFormProvider => BaseRequestFormProvider.of(context, listen: false);

  String _currentDateText;

  @override
  Widget build(BuildContext context) {
    /// 显示的字符串
    var _dateTime = _baseRequestFormProvider.getDataSource(widget.request);

    ///处理当传入数据为Map的时候，取Map最后一个值的value显示
    if (_dateTime != null && (_dateTime is Map) && _dateTime.length != 0) {
      (_dateTime as Map).forEach((key, value) {
        _currentDateText = value.toString();
      });
    } else {
      _currentDateText = _dateTime ?? '';
    }
    _currentDateText = BaseTransformUtil.stringToDate(_currentDateText);
    return BaseRequestFormContainer(
      onPress: () => _openDatePicker(),
      request: widget.request,
      showSuffixIcon: !_baseRequestFormProvider.isReadonly(widget.request),
      suffixIcon: _buildIcon(),
      child: _currentDateText.length == 0 ? Text(widget.request.notes ?? '', style: Theme
          .of(context)
          .inputDecorationTheme
          .hintStyle) : Text(_currentDateText),
    );
  }

  _buildIcon() {
    return Container(child: Icon(BaseIconData.x3Date, color: BaseBodyTheme.iconColor, size: 16));
  }

  _openDatePicker() {
    DateTime currentDate = _currentDateText.length > 0 ? DateTime.parse(_currentDateText).toLocal() : null;
    DateTime firstDate;

    /// 判断是否now on date 类型
    if (widget.fromNowOn == true) {
      DateTime today = DateTime.now();
      firstDate = today;
      if (currentDate != null) {
        bool isBefore = today.isBefore(currentDate);
        if (isBefore == false) currentDate = today;
      }
    }
    BaseComponentUtils.openDatePicker(context, firstDate: firstDate, currentDate: currentDate, onDateChanged: (DateTime dateTime) {
      String date = BaseTransformUtil.dateTimeAsString(dateTime);
      setState(() {
        _baseRequestFormProvider.setDataSource(widget.request, date);
      });
      if (widget.requestSaveData != null) widget.requestSaveData(widget.request, _baseRequestFormProvider.getMapDataSource(widget.request));
    });
  }
}
